package com.all.proxy.handler;

import lombok.extern.slf4j.Slf4j;
import net.bytebuddy.ByteBuddy;
import net.bytebuddy.implementation.InvocationHandlerAdapter;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;

/**
 * @Author LY
 * @create 2024/5/11 14:54
 * @Description ByteBuddy动态代理实现
 */
@Slf4j
public class ByteBuddyProxyHandler implements InvocationHandler {

    private Object target;//代理目标类

    public ByteBuddyProxyHandler(Object target) { //构造方法
        this.target = target;
    }

    public <T> T getProxy(Class<T> clazz) {
        try{
            log.info("基于ByteBuddy动态代理...");
            return (T) new ByteBuddy().subclass(Object.class)
                    // 实现接口
                    .implement(clazz)
                    // 实现调用
                    .intercept(InvocationHandlerAdapter.of(this))
                    // 生成代理类字节码
                    .make()
                    // 加载指定的类加载器
                    .load(ByteBuddyProxyHandler.class.getClassLoader())
                    // 获取加载的代理类
                    .getLoaded()
                    // 获取代理类构造函数
                    .getDeclaredConstructor()
                    // 创建实例
                    .newInstance();
        }catch (Exception e){
            log.error("bytebuddy proxy throws exception:{}", e);
        }
        return null;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        System.out.println("Before method: " + method.getName());
        Object result = method.invoke(target, args);
        System.out.println("After method: " + method.getName());
        return result;
    }
}
